// pages/pay/pay.js
import axios from '../../utils/axios';
import checkSub from '../../utils/checkSub';
import dayjs from 'dayjs';
import { imgFormat } from '../../utils/imgFormat';

const formatTime = 'YYYY-MM-DD HH:mm';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    item: {},
    orderDetail: {},
    timePeriod: '',
    duration: 0,
    amount: 0,// 费用小计
    balance:"0.00",// 会员余额
    price:0,// 应付金额
    yezf:[{value:"v",checked:true}],
    isYezf:false, //会员余额支付复选框
  },
  checkboxChange: function (e) {  
    // 当复选框的选中状态发生变化时，会触发checkboxChange事件  
    // e.detail.value数组中包含了所有选中项的value值  
    const isYezf = e.detail.value.length === 1;
    const {price,balance} = this.data;
    if(isYezf){
      console.log(1)
      // 使用余额支付
      let amount = 0;
      if(balance >= price){
        amount = 0
      }else{
        amount -=balance;
      }
      amount=amount.toFixed(2);
      this.setData({
        amount,
        isYezf
      })
    }else{
      console.log(2);
      this.setData({
        amount:price.toFixed(2),
        isYezf
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.openid = wx.getStorageSync('openid');
    if (options && options.item) {
      const item = JSON.parse(options.item);
      item.banners = imgFormat(item.banners);
      this.setData({ item });
    } else {
      wx.switchTab({
        url: `/pages/home/home`,
      });
    }
  },

  onShow() {
    this.queryBalance();
  },
  queryBalance(){
    axios.get("/app/memberList",{
      wxId:wx.getStorageSync('openid')
    }).then(res=>{
      this.getOrderDetail(this.data.item);
      const balance = res.data[0].balance.toFixed(2);
      const isYezf = balance > 0;
      this.setData({
        balance,
        isYezf
      })
    })
  },
  async getOrderDetail(item = {}) {
    const { orderId,renew } = item;
    const res = await axios.get(`/app/orderList?wxId=${this.openid}&ID=${orderId}`);
    let orderDetail = res?.data?.[0];
    if(renew){
      //续费
      orderDetail={
        ...orderDetail,
        startTime: item.startTime,
        endTime: item.endTime,
        price: item.price,
      }
    }
    // 续费等等再做, 需要考虑预约时间是否接着上一单
   
    const timePeriod = `${dayjs(orderDetail.startTime).format(formatTime)} - ${dayjs(orderDetail.endTime).format(
      'HH:mm',
    )}`;
    const duration = dayjs(orderDetail.endTime).diff(dayjs(orderDetail.startTime), 'hour');
    let price = orderDetail.price;
    let amount = price;
    const balance = this.data.balance;
    if(balance >= price){
      amount = 0
    }else{
      amount -=balance;
    }
    amount=amount.toFixed(2);
    this.setData({ orderDetail, timePeriod, duration, amount,price });
  },

  wxPay(amounts){
    const { orderId } = this.data.item;
    axios.post('/app/toPay', {
      openid: this.openid,
      orderId,
      name: `偶遇京城（${this.data.item.shopName})${this.data.item.name}`,
      payment:amounts.price*1,
      balance:amounts.balance*1
    })
    .then((res) => {
      if(res.data === "success"){
        this.payCallback()
        return ;
      }
      const { nonceStr, timeStamp, signType, paySign } = res.data;
      const that = this;
      wx.requestPayment({
        timeStamp,
        nonceStr,
        package: res.data.package,
        signType,
        paySign,
        success() {
          that.payCallback()
        },
        fail() {
          wx.showToast({
            title: '支付取消',
            icon: 'error'
          })
        },
      });
    });
  },
  pay() {
    // price：原价
    // balance: 会员余额
    // amount：应付金额
    const {price,isYezf,balance,amount} = this.data;
    if(isYezf){
      if(balance >= price){
        //余额支付 ，余额足够支付
        this.wxPay({
          price:0,
          balance:price
        });
      }else{
        // 有余额，但是不够订单金额，扣余额并支付
        this.wxPay({
          price:amount,
          balance
        });
      }
    }else{
      // 不使用会员余额
      this.wxPay({
        price,
        balance:0
      });
    }
  },
  payCallback(){
    wx.showToast({
      title: '支付成功',
      icon: 'none'
    })
    const { orderId } = this.data.item;
    checkSub(['ZAen9G6QJvaBN_B8itISxyfmf2bL5vPHNyGC8WRPOKE']).finally(() => {
      wx.redirectTo({
        url: `/pages/result/pay/index?orderId=${orderId}`,
      });
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
